package com.tseng.examples;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.json.JSONArray;
import org.json.JSONObject;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;


public class ConnectClass {
	final int TIMEOUT_MILLISEC =30000; //30secs
/** Called when the activity is first created. */

	/*@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		String JSONServerObject = getJSONArray();
		try {
			JSONArray jsonArray = new JSONArray(JSONServerObject);
			Log.i(ConnectClass.class.getName(),
					"Number of entries " + jsonArray.length());
			for (int i = 0; i < jsonArray.length(); i++) {
				JSONObject jsonObject = jsonArray.getJSONObject(i);
				Log.i(ConnectClass.class.getName(), jsonObject.getString("PASSWORD"));
				/*view the page(http://www.suopensim.com/connect.php) to get an idea of what 
				 * and how json are sent. you can catch them with position location 
				 * similar to an array or you can blantly check for the correct text field. 
				 *//*
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		//Toast.makeText("It works");
		sendToServer();
	}*/
	public void login(String username, String password)
	{
		
		
		
	}
	public String getJSONArray() {
		StringBuilder builder = new StringBuilder();
		HttpClient client = new DefaultHttpClient();
		
		HttpGet httpGet = new HttpGet(
				"http://www.suopensim.com/app/fromserver.php");
		/*view the page to get an idea of what 
		 * and how json are sent. you can catch them with position location 
		 * similar to an array or you can blantly check for the correct text field. 
		 */
														
		try {
			HttpResponse response = client.execute(httpGet);
			StatusLine statusLine = response.getStatusLine();
			int statusCode = statusLine.getStatusCode();
			if (statusCode == 200) {
				HttpEntity entity = response.getEntity();
				InputStream content = entity.getContent();
				BufferedReader reader = new BufferedReader(
						new InputStreamReader(content));
				String line;
				while ((line = reader.readLine()) != null) {
					builder.append(line);
				}
			} else {
				Log.e(ConnectClass.class.toString(), "Failed to download file");
			}
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return builder.toString();
	}
	
	public void sendToServer() {
	    try {
	        JSONObject json = new JSONObject();
	        json.put("UserName", "test2");
	        json.put("FullName", "1234567");
	        HttpParams httpParams = new BasicHttpParams();
	        HttpConnectionParams.setConnectionTimeout(httpParams,
	                TIMEOUT_MILLISEC);
	        HttpConnectionParams.setSoTimeout(httpParams, TIMEOUT_MILLISEC);
	        HttpClient client = new DefaultHttpClient(httpParams);
	        String url = "http://www.suopensim.com/app/toserver.php";

	        HttpPost request = new HttpPost(url);
	        request.setEntity(new ByteArrayEntity(json.toString().getBytes(
	                "UTF8")));
	        request.setHeader("json", json.toString());
	        HttpResponse response = client.execute(request);
	        HttpEntity entity = response.getEntity();
	        // If the response does not enclose an entity, there is no need
	        if (entity != null) {
	            InputStream instream = entity.getContent();

	            String result = convertStreamToString(instream);
	            Log.i("Read from server", result);
				Log.e(ConnectClass.class.getName(),
						this + result);
	        }
	    } catch (Throwable t) {
			Log.e(ConnectClass.class.getName(), "Request failed: " + t.toString());

	    }
	}
    public static String convertStreamToString(InputStream is) {
	    /*
	   * To convert the InputStream to String we use the BufferedReader.readLine()
	    * method. We iterate until the BufferedReader return null which means
	    * there's no more data to read. Each line will appended to a StringBuilder
	  * and returned as String.
	    */
	  BufferedReader reader = new BufferedReader(new InputStreamReader(is));
	    StringBuilder sb = new StringBuilder();

	    String line = null;
	   try {
	     while ((line = reader.readLine()) != null) {
	          sb.append(line + "\n");
	     }
	  } catch (IOException e) {
	    e.printStackTrace();
	 } finally {
	     try {
	       is.close();
	  } catch (IOException e) {
	      e.printStackTrace();
	    }
	}
	return sb.toString();
	}
}